import {Token} from "../../../data/decoder/token";
import {gotoIndex} from "../../../utils/navigate";
import flarum from "../../../flarum";
import {checkLoginStatus, getFlarum, setStorage} from "../../../utils/util";

const app = getApp()
Page({
    data: {
        login:{
            username: '',
            password: ''
        },
        flarum: {},
        logo: ""
    },
    onLoad: function (options) {
        const loginStatus = checkLoginStatus()
        if (loginStatus.isLogin === true) {
            gotoIndex()
        }
        const that = this
        let logo
        const flarumInfo = getFlarum() ?? {}
        switch (flarum.driver.displayLogin) {
            case "logo":
                logo = flarumInfo.logoUrl
                break;
            case "favicon":
            default:
                logo = flarumInfo.faviconUrl
        }
        that.setData({
            flarum: flarumInfo,
            logo: logo
        })

        wx.lin.initValidateForm(that)
    },
    submit: function(e) {
        const username = e.detail.values.username,
            password = e.detail.values.password

        if (username === "" || password === "") {
            wx.showToast({
                title: '用户名和密码不能为空',
                icon: 'error',
                duration: 2000
            })

        }else{
            const token = new Token();
            token.execute(username, password, function(data, viewData) {
                const uid = data.userId,
                    identity = data.token

                setStorage(flarum.cache.identity, {
                    "identity": identity,
                    "uid": uid
                })
                gotoIndex()
            })
        }
    }
});